package com.dragon.queue;

/**
 * 数组队列
 *
 * @author dragon
 * @since 2019/11/19
 */
public class ArrayQueue {

    /**
     * 存放元素的数组容器
     */
    private int[] elementData;

    /**
     * 记录队列的头部角标
     */
    private int head;

    /**
     * 记录队列的尾部角标
     */
    private int tail;

    /**
     * 记录队列存储的实际的元素个数
     */
    private int size;

    /**
     * 默认的容量
     */
    private static final int DEFAULT_CAPACITY = 5;


    public ArrayQueue(int capacity) {
        if (capacity <= 0) {
            capacity = DEFAULT_CAPACITY;
        }
        elementData = new int[capacity];
        tail = -1;
    }

    public ArrayQueue() {
        this(DEFAULT_CAPACITY);
    }

    /**
     * 入队列
     *
     * @param num
     */
    public void enqueue(int num) {
        if (isFull()) {
            throw new RuntimeException("ArrayQueue is Full");
        }
        elementData[++tail] = num;
        ++size;
    }

    /**
     * 出队列
     *
     * @return
     */
    public int dequeue() {
        if (isEmpty()) {
            throw new RuntimeException("ArrayQueue is Empty");
        }
        --size;

        return elementData[head++];
    }

    /**
     * 显示队列中队首的值
     *
     * @return 队列中队首的值
     */
    public int peek() {
        if (isEmpty()) {
            throw new RuntimeException("ArrayQueue is Empty");
        }

        return elementData[head];
    }

    /**
     * 判断队列是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return this.size == 0;
    }

    /**
     * 判断队列是否满了，就是说现在的这个队列不是一个循环队列，只能往数组后面添加元素，直到添加到数组的最大角标的时候，就满了
     *
     * @return 是否队列已满
     */
    public boolean isFull() {
        return this.tail == elementData.length - 1;
    }

    /**
     * 展示队列元素
     */
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("ArrayQueue is Empty");
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("tail ");
        for (int i = tail; i >= head; i--) {
            if (i == head) {
                sb.append(elementData[i] + " head");
                break;
            }
            sb.append(elementData[i] + ",");
        }

        System.out.println(sb.toString());
    }

    /**
     * 返回队列的元素个数
     *
     * @return 元素个数
     */
    public int size() {
        return this.size;
    }
}
